let app = getApp()
const observer = require("../../common/lib/observer").observer
let store = require("home_store").store
let ble = require("../../util/ble")
let mqtt = require("../../util/mqtt")
let op_code = require("../../util/op_code")
let settings = require("../../util/settings")


Page(observer({
	props: {
		common_store: app.data.common_store,
		store: new store(),
	},
	onShow() {
		this.props.common_store.input_code.op_type = "home"
		// ble.open_bt()
		// ble.get_bt_state()
		this.mqtt_connect()
		// this.calcMsgBodyHeight()

	},
	onLoad() {
		settings.get_settings()
	},
	go(item)  {
		app.go(item)
	},
	
	discovery_cw() {
		if(this.props.common_store.bt_dev.c_dev.connected) {
			// 断开连接
			ble.close_dev()
		}
		else {
			// 连接设备
			ble.ble_start()
		}
	},
	
	mqtt_con() {
		if(!this.props.common_store.mqtt.connected) {
			this.mqtt_connect()
		}
		else {
			mqtt.end()
		}
	},
	// 连接MQTT
	mqtt_connect() {
		console.log("mqtt connecting...")
		mqtt.connect().then(() => {
			// mqtt.send("-.-. --.-  -.-. --.-  -.-. --.-  -.. .  -... --. --... -.-- -..- -.--  -... --. --... -.-- -..- -.--  .--. ... .  -.-")	
			this.props.common_store.mqtt.conn.on("message", (topic, message, packet) => {
				if(topic == this.props.common_store.mqtt.topic) {
					this.mqtt_rec_msg(message)
				}
			})
			this.props.common_store.mqtt.conn.on("end", () => {
				console.log("mqtt  end --")
			})
		})
	},

	mqtt_rec_msg(msg) {
		msg = msg.toString()
		msg = msg.split(this.props.common_store.mqtt.split_code)
		if(msg.length == 3) {
			let client_id = msg[0]
			let callsign = msg[1]
			let code = msg[2]
			// console.log(client_id)
			if(client_id == this.props.common_store.mqtt.options.clientId) {
				this.push_show_msg("self", callsign, code)
			}
			else {
				this.push_show_msg("other", callsign, code)
			}
		}
		else if (msg.length == 2) {
			let callsign = msg[0]
			let code = msg[1]
			this.push_show_msg("other", callsign, code)
		}
	},
	push_show_msg(msg_type, callsign, code) {
		if(msg_type == "other" || this.props.common_store.settings.play_my_code) {
			ble.send("ply:" + code);
		}
		if(this.props.common_store.settings.conv_code) {
			let conv_code = op_code.conv("c2w", code)
			code = code + "\n\n" + conv_code
		}
		this.props.store.msg_list.push({
			msg_type: msg_type,
			callsign: callsign,
			code: code,
			rec_time: this.get_time()
		})
		this.props.store.msg_bottom_view = "msg" + (this.props.store.msg_list.length - 1).toString()
	},
	get_time() {
		let date = new Date()
		let hour = date.getHours()
		let minute = date.getMinutes()
		let second = date.getSeconds()
		return hour.toString() + ":" + minute.toString() + ":" + second.toString()
	},
	send_code() {
		mqtt.send_code();	
	},
	del_code() {
		// mqtt.clear_code();
		mqtt.del_last();
	}
}))